import { RequestConfig } from 'umi';
import { createLogger } from 'redux-logger';
import { message } from 'antd';
// 引入viewerjs默认样式
import 'viewerjs/dist/viewer.css';

// 配置dva日志
export const dva = {
  config: {
    // onAction: createLogger(),
    onError(e: Error) {
      message.error(e.message, 3);
    },
  },
};

// 配置网络请求
let hasError = false;
const requestList: { method: string, url: string }[] = [];
const baseURL = 'https://creationapi.shbwyz.com';
export const request: RequestConfig = {
  timeout: 20000,
  errorConfig: {

  },
  middlewares: [],
  requestInterceptors: [(url, options) => {
    return {
      url: `${baseURL + url}`,
      options: { ...options, interceptors: true },
    };
  }],
  responseInterceptors: [
    (response : any) => {
      let index = requestList.findIndex(item => {
        if (item.url === response.url) {
          return true
        }
        return false;
      })
      if (index !== -1) {
        requestList.splice(index, 1);
      }
      const codeMaps: { [key: number]: string } = {
        400: '客户端请求错误',
        403: '请求不被允许',
        404: '接口不存在',
        500: '服务器内部错误',
        502: '网关错误。',
        503: '服务不可用，服务器暂时过载或维护。',
        504: '网关超时。',
      };
      if (Object.keys(codeMaps).indexOf(String(response.status)) !== -1) {
        if (!hasError) {
          hasError = true;
          message.error({
            content: codeMaps[response.status],
            onClose: () => {
              hasError = false;
            }
          });
          return response.body;
        }
      } else {
        return response;
      }
      return {};
    }
  ],
};
